package com.link.play.fit.ai.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import androidx.appcompat.widget.AppCompatImageView

class DraggableImageView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

    // 系统认为的最小滑动距离
    private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop

    // 记录初始位置
    private var lastX = 0f
    private var lastY = 0f
    private var downX = 0f
    private var downY = 0f
    private var isDragging = false

    // 点击事件监听器
    private var clickListener: OnClickListener? = null

    init {
        setOnTouchListener(::handleTouch)
    }

    override fun setOnClickListener(l: OnClickListener?) {
        clickListener = l
    }

    private fun handleTouch(v: View, event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                // 记录按下位置
                downX = event.rawX
                downY = event.rawY
                lastX = event.rawX
                lastY = event.rawY
                isDragging = false
            }

            MotionEvent.ACTION_MOVE -> {
                // 计算移动距离
                val deltaX = event.rawX - lastX
                val deltaY = event.rawY - lastY

                // 更新位置
                x += deltaX
                y += deltaY

                // 限制在父容器内
                constrainToParent()

                // 更新最后位置
                lastX = event.rawX
                lastY = event.rawY

                // 判断是否达到拖动阈值
                if (!isDragging) {
                    val dx = event.rawX - downX
                    val dy = event.rawY - downY
                    if (dx * dx + dy * dy > touchSlop * touchSlop) {
                        isDragging = true
                    }
                }
            }

            MotionEvent.ACTION_UP -> {
                // 未达到拖动阈值时触发点击
                if (!isDragging) {
                    clickListener?.onClick(this)
                }
            }
        }
        return true
    }

    // 限制在父容器范围内
    private fun constrainToParent() {
        val parentWidth = (parent as? View)?.width ?: return
        val parentHeight = (parent as? View)?.height ?: return

        x = x.coerceIn(0f, parentWidth - width.toFloat())
        y = y.coerceIn(0f, parentHeight - height.toFloat())
    }
}
